package com.sgb.jicai.view.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.qgb.zcore.event.WebEvent;
import com.sgb.jicai.R;
import com.sgb.jicai.base.JiCaiBaseApi;
import com.sgb.jicai.databinding.ActivityFactoryParticipationBinding;
import com.sgb.jicai.entity.FactoryParticipationEntity;
import com.sgb.jicai.entity.SubmitFactoryParticipationEntity;
import com.sgb.jicai.view.adapter.FactoryParticiShoppingListAdapter;
import com.sgb.jicai.viewmodel.FactoryParticipationModel;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.InvoiceManagementEntity;
import com.sgb.link.entity.WebSiteAddressEntity;
import com.sgb.link.event.LeaseEvent;
import com.swgk.core.base.AppActivity;
import com.swgk.core.base.aroute.ARouterStartWebBase;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;

/**
 * 供方发起 -- 立即参与 页面
 */
public class FactoryParticipationActivity extends AppActivity implements View.OnClickListener {

    FactoryParticipationModel model;
    ActivityFactoryParticipationBinding binding;
    private String no;
    private FactoryParticiShoppingListAdapter adapter;//采购清单列表适配器
    private int ADDRESS= 10021;

    //收货地址信息
    private WebSiteAddressEntity addressEntity;
    //开票信息
    private InvoiceManagementEntity invoiceManagementEntity;
    //最低采购量
    private String lowBuy;
    private String url = "";

    public static void start(Context context, String no,String url) {
        Intent intent = new Intent();
        intent.setClass(context, FactoryParticipationActivity.class);
        intent.putExtra("JICAIID", no);
        intent.putExtra("url", url);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected void initView() {
        super.initView();
        no = getIntent().getStringExtra("JICAIID");
        binding = DataBindingUtil.setContentView(this, R.layout.activity_factory_participation);
        model = new ViewModelProvider(this).get(FactoryParticipationModel.class);
        model.setActivity(FactoryParticipationActivity.this);
        url = getIntent().getStringExtra("url");
        binding.ivBack.setOnClickListener(this::onMultiClick);
        binding.llAddressHave.setOnClickListener(this::onMultiClick);
        binding.llAddressNo.setOnClickListener(this::onMultiClick);
        binding.llTicketHas.setOnClickListener(this::onMultiClick);
        binding.llTicketNo.setOnClickListener(this::onMultiClick);
        binding.tvSubmit.setOnClickListener(this::onMultiClick);

        adapter = new FactoryParticiShoppingListAdapter(this, null);
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.shape_list_divide2));
        binding.recyclerGuide.addItemDecoration(divider);
        binding.recyclerGuide.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerGuide.setAdapter(adapter);
        binding.recyclerGuide.setPullRefreshEnabled(false);
        binding.recyclerGuide.setLoadingMoreEnabled(false);
    }

    @Override
    protected void init() {
        super.init();
        //获取默认收货地址
        model.getAddressModel();
        //获取默认开票信息
        model.getBillList(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, ""));
        //获取数据
        model.getProductDetailForAddOrder(no);
    }

    @Override
    public void onMultiClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            if (!TextUtils.isEmpty(url)){
                JiCaiBaseApi.startWeb(this,url);
                finish();
            }else {
                finish();
            }
        } else if (id == R.id.ll_address_have || id == R.id.ll_address_no) {
            ARouterStartWebBase.startWebSiteAddress(this, 1, ADDRESS);
        } else if (id == R.id.ll_ticket_has || id == R.id.ll_ticket_no) {
            ARouterStartWebBase.starInvoiceManagement(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO, ""),1);
        } else if (id == R.id.tv_submit) {//提交
            submitParticipation();
        }
    }

    //提交参与信息
    private void submitParticipation() {
        if (null == addressEntity) {
            MToast.showToast(this, "请先选择收货地址信息");
            return;
        }
        if (null == invoiceManagementEntity) {
            MToast.showToast(this, "请先补充开票信息");
            return;
        }
        List<FactoryParticipationEntity> datas = adapter.getDatas();
        SubmitFactoryParticipationEntity entity = new SubmitFactoryParticipationEntity();
        entity.setSaleNo(no);
        entity.setRemark(binding.cevRemark.getEditContent());
        //组装收货信息
        entity.setProvinceName(addressEntity.getProvince());
        entity.setProvinceNo(addressEntity.getProvinceNo());
        entity.setCityName(addressEntity.getCity());
        entity.setCityNo(addressEntity.getCityNo());
        entity.setDistrictName(addressEntity.getArea());
        entity.setDistrictNo(addressEntity.getAreaNo());
        entity.setDetailsAddress(addressEntity.getDetailAddress());
        entity.setContacts(addressEntity.getReceivePerson());
        entity.setContactNumber(addressEntity.getPhone());
        //组装开票信息
        entity.setBillingCompany(invoiceManagementEntity.getCompanyName());
        entity.setBillingAddress(invoiceManagementEntity.getAddress());
        entity.setBillingOpeningBank(invoiceManagementEntity.getBank());
        entity.setBillingIdentificationNumber(invoiceManagementEntity.getCreditCode());
        entity.setBillingPhoneNumber(invoiceManagementEntity.getPhone());
        entity.setBillingAccountNumber(invoiceManagementEntity.getBankNo());
        //组装采购清单信息
        List<SubmitFactoryParticipationEntity.DetailsEntity> detailsList = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            FactoryParticipationEntity participationEntity = datas.get(i);
            SubmitFactoryParticipationEntity.DetailsEntity detailsEntity = new SubmitFactoryParticipationEntity.DetailsEntity(participationEntity.getDetailNo(),
                    participationEntity.getPickTime(), participationEntity.getNum());

            detailsList.add(detailsEntity);
        }
        entity.setDetails(detailsList);

        double allPurchasedNum = 0;
        //判断第几条填写是否完整
        for (int i = 0; i < detailsList.size(); i++) {
            SubmitFactoryParticipationEntity.DetailsEntity detailsEntity = detailsList.get(i);
            if (null == detailsEntity.getPickTime() && (null != detailsEntity.getPurchaseNum() && !detailsEntity.getPurchaseNum().equals("0"))) {
                MToast.showToast(this, "第" + (1 + i) + "项未填写提货时间");
                return;
            }
            if ((null == detailsEntity.getPurchaseNum() || detailsEntity.getPurchaseNum().equals("0")) && null != detailsEntity.getPickTime()) {
                MToast.showToast(this, "第" + (1 + i) + "项未填写采购量");
                return;
            }
            if (null != detailsEntity.getPurchaseNum() && !detailsEntity.getPurchaseNum().equals("0") && null != detailsEntity.getPickTime() && !detailsEntity.getPurchaseNum().isEmpty() && !detailsEntity.getPickTime().isEmpty()) {
                //计算总量
                allPurchasedNum = allPurchasedNum + Double.valueOf(detailsEntity.getPurchaseNum());
            }
        }

        //判断是否有参与项
        boolean hasChange = false;
        for (int i = 0; i < detailsList.size(); i++) {
            SubmitFactoryParticipationEntity.DetailsEntity detailsEntity = detailsList.get(i);
            //至少有一条完整的参与项
            if (null != detailsEntity.getPurchaseNum() && null != detailsEntity.getPickTime() && !detailsEntity.getPurchaseNum().isEmpty() && !detailsEntity.getPickTime().isEmpty()) {
                hasChange = true;
                break;
            }
        }
        if (!hasChange) {
            MToast.showToast(this, "未填写采购清单，请添加采购量和提货时间");
            return;
        }
        if (null != lowBuy) {
            if (Double.valueOf(lowBuy) > allPurchasedNum) {
                MToast.showToast(this, "当前采购量小于采购起始量");
                return;
            }
        }

        String director = binding.director.getContent();
        if (null != director && !TextUtils.isEmpty(director)) {
            entity.setDirector(director);
        } else {
            MToast.showToast(this, "请填写负责人信息");
            return;
        }
        String directorNumber = binding.directorNumber.getText().toString().trim();
        if (null != directorNumber && !TextUtils.isEmpty(directorNumber)) {
            entity.setDirectorNumber(directorNumber);
        } else {
            MToast.showToast(this, "请填写负责人电话");
            return;
        }
        entity.setEmail(binding.email.getText().toString().trim());

        model.submitParticipationInfo(entity);
    }

    //数据返回后更新UI显示
    public void updateView(List<FactoryParticipationEntity> datas) {
        adapter.setDatas(datas);
        if (null != datas && datas.size() > 0) {
            lowBuy = datas.get(0).getLowBuy();
        }
    }

    public void submitSuccessDo() {
        WebEvent webEvent = new WebEvent();
        webEvent.setMessageTag(EventConstant.EVENT_WEBVIEW_RELOAD);
        EventBus.getDefault().post(webEvent);
        if (!TextUtils.isEmpty(url)){
            JiCaiBaseApi.startWeb(this,url);
            finish();
        }else {
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK){
           if (requestCode == ADDRESS){
               addressEntity =(WebSiteAddressEntity)  data.getSerializableExtra("data");
               setDefaultAddress();
           }
        }
    }

    public void showAddressList(List<WebSiteAddressEntity> addressEntityList) {
        if (null != addressEntityList && addressEntityList.size() > 0) {
            WebSiteAddressEntity addressEntity = null;
            for (int i = 0; i < addressEntityList.size(); i++) {
                if (addressEntityList.get(i).isDefaultAddress()) {
                    addressEntity = addressEntityList.get(i);
                    break;
                }
            }
            if (null != addressEntity) {
                this.addressEntity = addressEntity;
                setDefaultAddress();
            } else {
                binding.llAddressNo.setVisibility(View.VISIBLE);
                binding.llAddressHave.setVisibility(View.GONE);
            }
        } else {
            binding.llAddressNo.setVisibility(View.VISIBLE);
            binding.llAddressHave.setVisibility(View.GONE);
        }
    }

    public void showBillList(List<InvoiceManagementEntity> billList) {
        if (null != billList && billList.size() > 0) {
            InvoiceManagementEntity invoiceManagementEntity = null;
            for (int i = 0; i < billList.size(); i++) {
                if (billList.get(i).getIsDefault() == 1) {
                    invoiceManagementEntity = billList.get(i);
                    break;
                }
            }
            if (null != invoiceManagementEntity) {
                this.invoiceManagementEntity = invoiceManagementEntity;
                setDefauleBill();
            } else {
                binding.llTicketHas.setVisibility(View.GONE);
                binding.llTicketNo.setVisibility(View.VISIBLE);
            }
        } else {
            binding.llTicketHas.setVisibility(View.GONE);
            binding.llTicketNo.setVisibility(View.VISIBLE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LeaseEvent event) {
        switch (event.getMessageTag()) {
            case EventConstant.EVENT_JICAI_FACTORY_LIJICANYU_KAIPIAOXINXI:
                invoiceManagementEntity = (InvoiceManagementEntity) event.getMessageData();
                setDefauleBill();
                break;
        }
        EventBus.getDefault().removeStickyEvent(event);
    }

    //设置显示默认的收货地址
    public void setDefaultAddress() {
        if (null == addressEntity) return;
        binding.llAddressNo.setVisibility(View.GONE);
        binding.llAddressHave.setVisibility(View.VISIBLE);
        binding.tvName.setText(addressEntity.getReceivePerson());
        binding.tvTel.setText(addressEntity.getPhone());
        binding.tvAddress.setText(addressEntity.itemDetailAddress());
    }

    //设置显示默认的开票信息
    public void setDefauleBill() {
        if (null == invoiceManagementEntity) return;
        binding.llTicketHas.setVisibility(View.VISIBLE);
        binding.llTicketNo.setVisibility(View.GONE);
        binding.tvCompanyName.setText(invoiceManagementEntity.getCompanyName());
        binding.tvTaxNum.setText(invoiceManagementEntity.getCreditCode());
        binding.tvBankAddress.setText(invoiceManagementEntity.getAddress());
        binding.tvBankPhone.setText(invoiceManagementEntity.getPhone());
        binding.tvBank.setText(invoiceManagementEntity.getBank());
        binding.tvBankNo.setText(invoiceManagementEntity.getBankNo());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}